import React, { useEffect, useState } from 'react';
import { Modal, Input, Button, Table, Space } from 'antd';
import { openNotification_util } from '../util/util';

const Popup_select = ({ onOk,initdata }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [label, setLabel] = useState('');
  const [value, setValue] = useState('');
  const [data, setData] = useState(initdata);

  const handleOpenModal = () => {
    setModalVisible(true);
  };

  const handleCloseModal = () => {
    setModalVisible(false);
  };

useEffect(() => {
  setData(initdata);
}, [initdata]);

  const handleSave = () => {
    if (!isTextDuplicate()) {
      onOk(JSON.stringify(data));

      setModalVisible(false);
    } else {
      openNotification_util('不允许添加重复值!');
    }
  };

  const handleAdd = () => {
    if (label && value) {
      if (!isTextDuplicate()) {
        setData([...data, { key: Date.now(), label, value }]);
        setLabel('');
        setValue('');
      } else {
        openNotification_util('不允许添加重复值!');
      }
    }
  };

  const isTextDuplicate = () => {
    return data.some((item) => item.value === value);
  };

  const handleDelete = (key) => {
    const updatedData = data.filter((item) => item.key !== key);
    setData(updatedData);
  };

  const columns = [
    {
      title: '显示内容',
      dataIndex: 'label',
      key: 'label',
    },
    {
      title: '值',
      dataIndex: 'value',
      key: 'value',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => handleDelete(record.key)}>删除</a>
        </Space>
      ),
    },
  ];

  return (
    <div >
      <div style={{width:"100%",height:"100%"}}
        onClick={handleOpenModal}
       >{data.length==0?'点击添加':data.map(item=>{
        return <div >{item.label}：{item.value}</div>
       })}</div>

      <Modal
        visible={modalVisible}
        title="配置下拉框选择项"
        onCancel={handleCloseModal}
        onOk={handleSave}
        width={600} // 设置弹窗宽度
        style={{ top: 20 }} // 设置弹窗距离顶部的位置
        destroyOnClose // 关闭时销毁 Modal 里的子元素
        footer={[
          <Button key="save" type="primary" onClick={handleSave}>
            保存
          </Button>,
        ]}
      >
       显示内容： <Input style={{marginTop:"1%",borderRadius:"5px",width:"60%"}}
          placeholder="请输入显示内容..."
          value={label}
          onChange={(e) => setLabel(e.target.value)}
        /><br/>
     &nbsp;&nbsp;&nbsp;  &nbsp;&nbsp;值：&nbsp;&nbsp;&nbsp;&nbsp; 
     <Input style={{marginTop:"1%",borderRadius:"5px",width:"60%"}}
          placeholder="请输入值..."
          value={value}
          onChange={(e) => setValue(e.target.value)}
        />
        <br/>
        <Button type="primary" onClick={handleAdd}>
          添加
        </Button>
        <Table columns={columns} dataSource={data} pagination={false} />
      </Modal>
    </div>
  );
};

export default Popup_select;